package com.mjf.cjt.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.mjf.cjt.config.OpenApiConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

@Configuration
@Slf4j
public class TMHttpUtils {

    private static final String TOKEN_URL = "/v1/common/auth/selfBuiltApp/generateToken";
    @Autowired
    private OpenApiConfig openApiConfig;

    public HttpResponse doGet(String path,String param){
        String url = openApiConfig.getGatewayUrl() + path;
        if(param != null){
            url += "?" + param;
        }
        HttpRequest request = HttpUtil.createGet(url);
        initHeader(request);
        return request.execute();
    }
    public HttpResponse doGet(String path, String param, Map<String,String> headerMap){
        String url = openApiConfig.getGatewayUrl() + path;
        if(param != null){
            url += "?" + param;
        }
        HttpRequest request = HttpUtil.createGet(url);
        if(headerMap != null){
            request.addHeaders(headerMap);
        }
        initHeader(request);
        return request.execute();
    }

    public HttpResponse doPost(String path, String body, Map<String,String> headerMap){
        String url = openApiConfig.getGatewayUrl() + path;
        HttpRequest request = HttpUtil.createPost(url);
        if(body != null){
            request.body(body);
        }
        log.info("请求实体：{}",body);
        if(headerMap != null){
            request.addHeaders(headerMap);
        }
        initHeader(request);
        return request.execute();
    }

    private  void initHeader(HttpRequest request){
        request.header("appKey",openApiConfig.getAppKey());
        request.header("appSecret",openApiConfig.getAppSecret());
        request.header("Content-Type","application/json");
    }
    public String doGetToken(){
        String token = null;
        HttpResponse execute = doPost(TOKEN_URL, null,null);
        if(execute.isOk()){
            token = execute.body();
        }
        if(token == null){
            log.error("获取畅捷通token失败");
        }
        return token;
    }
}
